import { currentDates } from '../../utils/util'
const app = getApp()

Page({
  data: {
    upurl: app.globalData.upurl,
    imgurl: app.globalData.imgurl,
    name: '',
    relation: '',
    currentDate: '',
    birthday: null,
    fileList: [],
    activeNames: [],
    //时间的隐藏
    showTime: false,
    minDate: new Date(2000, 0, 0).getTime(),
    flag: false,
    ub_id: 0,
  },

  onLoad: function ({ only }) {
    if (only) {
      console.log(only)

      let { pic, name, relation, birthday, ub_id } = JSON.parse(only)
      this.setData({
        flag: true,
        name,
        relation,
        currentDate: birthday,
        birthday: new Date(birthday).getTime(),
        'fileList[0]': { url: pic },
        ub_id,
      })
    }
  },
  async _del() {
    const { ub_id } = this.data
    let { code, data } = await wx.requestAsync({
      url: '/baby/del',
      data: {
        ub_id,
      },
    })
    if (code == 0) {
      wx.showToast({
        title: '删除成功',
        icon: 'none',
        duration: 2000,
        success: () => {
          setTimeout(() => {
            wx.redirectTo({
              url: '/pages/baby/baby',
            })
          }, 1000)
        },
      })
    }
  },
  async submit() {
    const { name, relation, birthday, pic, ub_id } = this.data
    let { code, data } = await wx.requestAsync({
      url: '/baby/add',
      data: {
        ub_id,
        name,
        relation,
        birthday: birthday / 1000,
        pic,
      },
    })
    if (code == 0) {
      wx.showToast({
        title: '添加成功',
        icon: 'none',
        duration: 2000,
      })
      wx.redirectTo({
        url: '/pages/baby/baby',
      })
    }
  },
  //关闭时间
  onCloseTime() {
    this.setData({ showTime: false })
  },
  _gettime({ detail }) {
    this.setData({
      birthday: detail,
      currentDate: currentDates(detail, 1),
      showTime: false,
    })
  },
  onChangeActive({ detail }) {
    this.setData({
      activeNames: detail,
    })
    if (detail == 3) {
      this.setData({ showTime: true })
    }
  },
  onChangeName({ detail }) {
    this.setData({
      name: detail,
    })
  },
  onChangeRelation({ detail }) {
    this.setData({
      relation: detail,
    })
  },

  afterRead(event) {
    const { file } = event.detail
    const { upurl, imgurl } = this.data
    const _this = this
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      header: {
        'auth-token': wx.getStorageSync('token') || '',
      },
      url: upurl, // 仅为示例，非真实的接口地址
      filePath: file.path,
      name: 'file',
      formData: { user: 'test' },
      success({ data }) {
        let res = JSON.parse(data)
        _this.setData({
          'fileList[0]': {
            url: imgurl + res.data.save_name,
          },
          pic: res.data.save_name,
        })
      },
    })
  },
})
